<template>
  <div class="user-management">
    <!-- 用户列表区域 -->
    <el-card class="user-list">
      <div class="header">
        <el-button type="success" icon="el-icon-plus" @click="openAddUser">新增用户</el-button>
        <el-button type="primary" icon="el-icon-search" @click="showAllUsers">查看全部用户</el-button>
        <el-input
          v-model="searchUser"
          placeholder="请输入用户名"
          class="search-input"
          prefix-icon="el-icon-search"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="searchUserByName">搜索</el-button>
      </div>
      <el-table
        :data="filteredUserList"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="userName"
          label="用户名"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="groupName"
          label="组名"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="permissionRole"
          label="权限角色"
          width="120"
           :formatter="formatPermissionRole"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="failedLoginNum"
          label="登录失败次数"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="accountLocked"
          label="账户锁定状态"
          width="120"
        ></el-table-column>
        <!-- <el-table-column
          label="操作"
          width="180"
        >
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="editUser(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteUser(scope.row)">删除</el-button>
          </template> -->
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      :title="isAdd ? '新增用户' : '编辑用户'"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form ref="userForm" :model="userForm" label-width="110px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <!-- <el-form-item label="邮箱">
          <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input> -->
        </el-form-item>
        <el-form-item label="口令" v-if="isAdd">
          <el-input
            type="password"
            v-model="userForm.password"
            placeholder="请输入口令"
          ></el-input>
        </el-form-item>
        <el-form-item label="再确认一次口令" v-if="isAdd">
          <el-input
            type="password"
            v-model="userForm.confirmPassword"
            placeholder="请再次输入口令"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui';
import axios from 'axios';

const API_BASE_URL = 'http://localhost:8081';

export default {
  data() {
    return {
      userList: [],
      searchUser: '',
      dialogVisible: false,
      isAdd: true,
      userForm: {
        userName: '',
        groupName: '',
        permissionRole: '',
        email: '',
        password: '',
        confirmPassword: '',
        failedLoginNum: 0,
        accountLocked: false
      },
      filteredUserList: []
    };
  },
  created() {
    this.showAllUsers();
  },
  methods: {
    openAddUser() {
      this.isAdd = true;
      this.userForm = {
        userName: '',
        groupName: '',
        permissionRole: '',
        email: '',
        password: '',
        confirmPassword: '',
        failedLoginNum: 0,
        accountLocked: false
      };
      this.dialogVisible = true;
    },
    editUser(row) {
      this.isAdd = false;
      this.userForm = { ...row };
      // 编辑时不显示密码相关字段，可根据需求调整
      delete this.userForm.password;
      delete this.userForm.confirmPassword;
      this.dialogVisible = true;
    },
    formatPermissionRole(row) {
      if (row.permissionRole == false) {
        return '管理员';
      } else if (row.permissionRole == true) {
        return '用户';
      }
      return '未知';
    },
    async saveUser() {
      if (this.isAdd) {
        if (this.userForm.password !== this.userForm.confirmPassword) {
          Message.error('两次密码不一致');
          return;
        }
        try {
          await axios.post(`${API_BASE_URL}/cuser/addUser`, {
            userName: this.userForm.userName,
            //email: this.userForm.email,
            password: this.userForm.password
          });
          Message({
            message: '新增用户成功',
            type: 'success',
            duration: 2000,
            offset: 50
          });
          this.showAllUsers();
          this.dialogVisible = false;
        } catch (error) {
          Message.error('新增失败');
          console.error(error);
        }
      } 
    },
     async searchUserByName() {
    try {
      const response = await axios.get(`${API_BASE_URL}/cuser/findByUserName?userName=${this.searchUser}`);
      if (response.data && response.data.data) {
        // 检查返回的数据是否为数组，如果不是则包装成数组
        if (Array.isArray(response.data.data)) {
          this.filteredUserList = response.data.data;
        } else {
          this.filteredUserList = [response.data.data];
        }
      } else {
        Message.error('返回数据格式不正确');
        return;
      }
    } catch (error) {
      Message.error('搜索失败');
    }
  },
    async showAllUsers() {
    try {
      const response = await axios.get(`${API_BASE_URL}/cuser/findAll`);
      // 检查返回数据结构，提取实际用户列表
      if (response.data && response.data.data) {
        this.userList = response.data.data;
        this.filteredUserList = response.data.data;
      } else {
        Message.error('返回数据格式不正确');
        return;
      }
      this.searchUser = '';
    } catch (error) {
      Message.error('获取用户列表失败');
      console.error(error);
    }
  }
  }
};
</script>

<style scoped>
.user-management {
  padding: 20px;
}
.user-list {
  margin-bottom: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.search-input {
  width: 300px;
}
</style>